<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/20
 * Time: 11:49
 */

namespace merchants;


use think\Controller;
use think\Exception;

class Bank extends Controller
{
    /**
     * 实时代收
     */
    public function agentpay(){
        $getConfig=Config::getConfig();
        $config=Config::Config();
        $info=$getConfig['agentpay'];
        // step1: 拼接报文及配置
        $transCode = $info['transCode']; // 交易码
        $accessType = '0'; // 接入类型 0-商户接入，默认；1-平台接入
        $merId = $info['merId']; // 此处更换商户号
        $path = $info['url']; // 服务地址
        $pt = $info['pt']; // 报文

        // step2: 生成AESKey并使用公钥加密
        $with=new WithdrawBank();
        $AESKey = aes_generate(16);
        $encryptKey = $with->RSAEncryptByPub($AESKey, $config['pubKey']);
        // step3: 使用AESKey加密报文
        $encryptData = $with->AESEncrypt($pt, $AESKey);
        // step4: 使用私钥签名报文
        $sign = $with->sign($pt, $config['priKey']);
        // step5: 拼接post数据
        $post = array(
            'transCode' => $transCode,
            'accessType' => $accessType,
            'merId' => $merId,
            'encryptKey' => $encryptKey,
            'encryptData' => $encryptData,
            'sign' => $sign
        );

        // step6: post请求
        $result = $with->http_post_json(API_HOST . $path, $post);
        parse_str($result, $arr);

        try {
            // step7: 使用私钥解密AESKey
            $decryptAESKey = $with->RSADecryptByPri($arr['encryptKey'], $config['priKey']);

            // step8: 使用解密后的AESKey解密报文
            $decryptPlainText =$with->AESDecrypt($arr['encryptData'], $decryptAESKey);

            // step9: 使用公钥验签报文
            $with->verify($decryptPlainText, $arr['sign'], $config['pubKey']);
        } catch (Exception $e) {
            echo $e->getMessage();
            exit;
        }

        print_r($decryptPlainText);
    }
}